package player

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/sp"
	"strings"

	log "github.com/sirupsen/logrus"
)

// 6501 玩家英雄
func (p *Player) HerosRequest(req *sp.HerosRequest) (res *sp.HerosResponse, err error) {

	lst, sendCount := lib.HerosInfo(p.User)
	res = &sp.HerosResponse{
		List:      lst,
		SendCount: sendCount,
	}
	return
}

// 6502 英雄信息
func (p *Player) HeroInfoRequest(req *sp.HeroInfoRequest) (res *sp.HeroInfoResponse, err error) {
	hero, ok := p.User.Heros().GetHeroByTid(req.Tid)
	if !ok {
		res = &sp.HeroInfoResponse{
			Errcode: data.Errcode.ServerErr,
		}
		return
	}
	res = &sp.HeroInfoResponse{
		Hero: lib.FormatHeroInfoSps(hero),
	}
	return
}

// 6503 已有英雄信息
func (p *Player) HeroListRequest(req *sp.HeroListRequest) (res *sp.HeroListResponse, err error) {
	lst, sendCount := lib.GetHeroList(p.User)
	res = &sp.HeroListResponse{
		HeroList:  lib.FormatHeroListSps(lst),
		SendCount: sendCount,
	}
	return
}

// 6505 赠送英雄卡片
func (p *Player) GiveHeroGoodRequest(req *sp.GiveHeroGoodRequest) (res *sp.GiveHeroGoodResponse) {
	if req.Tid == 0 || req.Uid == "" {
		res = &sp.GiveHeroGoodResponse{
			Errcode: data.Errcode.ServerErr,
		}
		return
	}

	uProp, err := lib.GiveHeroGood("GiveHeroGoodRequest", p.User, req.Tid, p.Send)
	if err != nil {
		log.WithFields(log.Fields{
			"method": "GiveHeroGoodRequest",
			"err":    err,
		}).Error("赠送卡片失败")
		res = &sp.GiveHeroGoodResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})

	utils.AsyncFunc(func() {
		p.giveHeroGoodNotice(req.Uid, req.Tid, p.User.Name)
	})

	res = &sp.GiveHeroGoodResponse{
		SendCount: 1,
	}
	return
}

// 6506 赠送英雄卡片通知
func (p *Player) giveHeroGoodNotice(uid string, tid int64, friendName string) {
	tPlayer, ok := GetPlayerByUid(uid)
	if !ok {
		log.WithFields(log.Fields{
			"method": "giveHeroGoodNotice",
			"uid":    uid,
		}).Error("赠送卡片失败")
		return
	}
	us := tPlayer.User

	// 19970224  好友的礼物卡片
	// 19970225  {0}赠送了卡片给你
	mailTitle, err := lib.GetLanguage("19970224", us.LangsTyp)
	if err != nil {
		log.WithFields(log.Fields{
			"method": "giveHeroGoodNotice",
			"err":    err,
		}).Error("获取标题失败")
		return
	}
	mailContent, err := lib.GetLanguage("19970225", us.LangsTyp)
	if err != nil {
		log.WithFields(log.Fields{
			"method": "giveHeroGoodNotice",
			"err":    err,
		}).Error("获取内容失败")
		return
	}
	mailContent = strings.Replace(mailContent, "{0}", friendName, 1)
	resGoods := make([]*m.Goods, 0)
	resGoods = append(resGoods, &m.Goods{Tid: tid, Num: 1})
	tPlayer.SendHeroMail(mailTitle, mailContent, resGoods)
}
